package com.open.cloud.rbac.utils;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

@Component
public class CacheUtil {
    /**
     * 缓存值的最大数
     */
    private int maximumSize = 10000;

    /**
     * 缓存过期分钟数
     */
//    private int expireAfterAccessMinutes = 60 * 72;
    private int expireAfterAccessMinutes = 5;

    private Cache<String, Object> _cache = null;

    public CacheUtil() {
        super();
    }

    public int getMaximumSize() {
        return maximumSize;
    }

    public void setMaximumSize(int maximumSize) {
        this.maximumSize = maximumSize;
    }

    public int getExpireAfterAccessMinutes() {
        return expireAfterAccessMinutes;
    }

    public void setExpireAfterAccessMinutes(int expireAfterAccessMinutes) {
        this.expireAfterAccessMinutes = expireAfterAccessMinutes;
    }

    //项目启动时加载
    @PostConstruct
    public void init() {
        _cache = CacheBuilder.newBuilder().maximumSize(this.maximumSize).expireAfterAccess(this.expireAfterAccessMinutes * 60, TimeUnit.SECONDS).build();
    }

    public Object get(String key) {
        return this._cache.getIfPresent(key);
    }

    public void put(String key, Object o) {
        this._cache.put(key, o);
    }

    public void invalidate(String key) {
        this._cache.invalidate(key);
    }
}

